import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AdminEbook from "@/views/admin/AdminEbook";
import AdminCategory from "@/views/admin/AdminCategory";
import AdminDoc from "@/views/admin/AdminDoc"
import AdminUser from "@/views/admin/AdminUser";
import store from "@/store";
import {isEmpty} from "@/util/Tool";
import Doc from "@/views/Doc";

const routes = [
  {
    path: '/',
    name: 'HomeView',
    component: HomeView
  },
  {
    path: '/adminEbook',
    name: 'AdminEbook',
    component: AdminEbook,
    meta:{
      loginRequire:true
    }
  },
  {
    path: '/adminCategory',
    name: 'AdminCategory',
    component: AdminCategory,
    meta:{
      loginRequire:true
    }
  },
  {
    path: '/adminDoc',
    name: 'AdminDoc',
    component: AdminDoc,
    meta:{
      loginRequire:true
    }
  },
  {
    path: '/doc',
    name: 'Doc',
    component: Doc
  },
  {
    path: '/adminUser',
    name: 'AdminUser',
    component: AdminUser,
    meta:{
      loginRequire:true
    }
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(
    (to, from, next)=>{
      const loginRequire = to.matched.some((item)=>{return item.meta.loginRequire})
      if (loginRequire) {
        const loginUser = store.state.user
        if (isEmpty(loginUser)) {
          next("/")
        } else {
          next()
        }
      } else {
        next()
      }
    }
)

export default router
